<?php
/**
 * Created by PhpStorm.
 * User: fengzb
 * Date: 2017/11/26
 * Time: 17:22
 */

namespace app\index\controller;

use app\index\Base;
use think\Db;
use think\Session;
use think\Url;

class Goods extends Base
{

    private $param;
    private $user;
    public function __construct(){
        parent::__construct();

        //提交的参数
        $this->param = $this->request->param();
        $this->user = Session::get('user');
    }

    /**
     * ajax 获取商品列表
     */
    public function get_list_by_ajax()
    {

        // 分页查询 每页显示10条
        $goods = Db::table('kyf_goods')->order('goods_id desc')->paginate(2, false, $this->request->param());
        $res = $goods->toArray();

        $result = array();
        $html_li = '';
        foreach ($res['data'] as $val) {
            $picarr = explode(',', $val['goods_pics']);
            $html_li .= '<li><a href="'.Url::build('index/goods/show',array('id'=>$val['goods_id'])).'">';
            $html_li .= '<img src="/public/'.$picarr[0] . '" class="img-responsive" alt="' . $val['goods_name'] . '">';
            $html_li .= '<div class="con"><h2>' . $val['goods_name'] . '</h2><div class="price">￥' . fmoney($val['price'], false) . '</div></div></a>';
            $html_li .= '<a class="cart" href="/addcart/id/' . $val['goods_id'] . '"><span class="mui-icon mui-icon-plus"></span>加入购物车</a></li>';
        }

        $result['htmlstr'] = $html_li;
        $result['code'] = 1;
        exit(json_encode($result));
    }

    /**
     * 详情页
     * @return string
     */
    public function show()
    {
        $params = $this->request->param();
        $id = isset($params['id']) ? intval($params['id']) : 0;
        if ($id == 0) {
            exit('参数错误');
        }

        $goods = Db::table('kyf_goods')->where('goods_id=' . $id)->find();

        // 详情页轮播必须5张图片
        $goods['picarr'] = explode(',',$goods['goods_pics']);
        array_push($goods['picarr'],$goods['picarr'][0]);
        $goods['price'] = fmoney($goods['price'],false);

        $this->view->assign('goods', $goods);

        return $this->view->fetch();
    }


    /**
     *  加入购物车
     */
    public function addCartOne(){
        $params = $this->param;
        $id = isset($params['id']) ? intval($params['id']) : 0;
        if($id==0){
            echo json_encode(array('code'=>1,'msg'=>'参数错误'));die();
        }
        $goods = Db::table('kyf_goods')->where('goods_id='.$id.' and status=1')->find();

        $buytype = isset($params['buy_type']) ? intval($params['buy_type']) : '1';
        $buynum = isset($params['buy_num']) ? intval($params['buy_num']) : '1';


        // 已经在购物车 就累加购买数量
        $where['goods_id'] = array('eq',$id);
        $where['status'] = array('eq',1);
        $where['uid'] = array('eq',$this->user['m_uid']);
        $where['buy_type'] = array('eq',$buytype);
        $cartinfo = Db::table('kyf_shopping_cart')->where($where)->find();
        if(!empty($cartinfo)){
            $srt = Db::table('kyf_shopping_cart')->where('cart_id=' . $cartinfo['cart_id'])->setInc('buy_num', $buynum);
            if($srt !== false){
                echo json_encode(array('code'=>0,'msg'=>'加入购物车成功'));die();
            }
        }


        $data['uid'] = $this->user['m_uid'];
        $data['goods_id'] = $id;
        $data['buy_num'] = $buynum;
        $data['buy_type'] = $buytype;
        $data['buy_price'] = $goods['price'];//按颗购买价

        $data['status'] = 1;
        $data['create_time'] = time();
        $data['goods_name'] = $goods['goods_name'];
        $data['short_name'] = $goods['short_name'];

        $cart_id = Db::table('kyf_shopping_cart')->insert($data,false,true);
        if($cart_id>0){
            echo json_encode(array('code'=>0,'msg'=>'加入购物车成功'));die();
        } else {
            echo json_encode(array('code'=>2,'msg'=>'加入购物车失败'));die();
        }
    }

    // 添加购物车成功
    function addCartSucc(){

        return $this->view->fetch();
    }


    // 购物车列表
    public function cartList(){
        $map['uid'] = array('eq',$this->user['m_uid']);
        $map['status'] = array('eq',1);

        $list = Db::table('kyf_shopping_cart')->where($map)->select();
        $total = 0;
        foreach ($list as &$val){
            $goodsinfo = Db::table('kyf_goods')->field('goods_pics,price')->where('goods_id='.$val['goods_id'])->find();
            $picarr = explode(',',$goodsinfo['goods_pics']);
            $val['goods_pic'] = $picarr[0];
            $count = $goodsinfo['price'] * $val['buy_num'];
            $total+= $count;
            $val['buy_price'] = fmoney($goodsinfo['price'],false);
        }

        $this->view->assign('total',fmoney($total,false));
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }

    /**
     * 从购物车移除
     */
    public function delCartGoods(){
        $params = $this->param;
        $cart_idstr = isset($params['id']) ? trim($params['id']) : '';
        if($cart_idstr==''){
            exit(json(array('code'=>1,'msg'=>'参数错误')));
        }
        $map['cart_id'] = array('in',$cart_idstr);
        $map['uid'] = array('eq',$this->user['m_uid']);
        $map['status'] = array('eq',1);

        $sava['status'] = 0;
        $srt = Db::table('kyf_shopping_cart')->where($map)->update($sava);
        if($srt!==false){
            exit(json(array('code'=>0,'msg'=>'删除成功')));
        } else {
            exit(json(array('code'=>1,'msg'=>'删除失败')));
        }
    }


    /**
     * 改变购买数量 只能++1 或者  --1
     */
    public function setBuynum(){
        $params = $this->param;
        $cart_id = isset($params['id']) ? intval($params['id']) : 0;
        $option = isset($params['option']) ? intval($params['option']) : 1;//  1  加1   0 减 1
        if($cart_id==0){
            exit(json(array('code'=>1,'msg'=>'参数错误')));
        }

        $map['cart_id'] = array('eq',$cart_id);
        $map['uid'] = array('eq',$this->user['m_uid']);

        if($option==1) {
            $srt = Db::table('kyf_shopping_cart')->where($map)->setInc('buy_num',1);
        } else {
            $srt = Db::table('kyf_shopping_cart')->where($map)->setDec('buy_num',1);
        }

        if($srt!==false){
            exit(json(array('code'=>0,'msg'=>'操作成功')));
        } else {
            exit(json(array('code'=>1,'msg'=>'操作失败')));
        }

    }


    /**
     * 去结算核对订单页面
     * @return string
     */
    public function confirmOrder(){
        $params = $this->param;
        $maps = array();
        if($this->user['m_uid'] <= 0){
            exit('用户信息已过期请重新登录');
        }

        if(isset($params['subcart']) && $params['subcart']==1 && $params['cartids']!=''){
            $cart_ids = trim($params['cartids'],',');
            $maps['cart_id'] = array('in',$cart_ids);
        }

        $maps['status'] = array('eq',1);
        $maps['uid'] = array('eq',$this->user['m_uid']);

        $list = Db::table('kyf_shopping_cart')->where($maps)->select();

        $goodstotal = 0;
        foreach ($list as &$val){
            $goods = Db::table('kyf_goods')->where('goods_id=' . $val['goods_id'])->find();
            $picarr = explode(',',$goods['goods_pics']);
            $val['goods_pic'] = $picarr[0];
            $count = $goods['price'] * $val['buy_num'];
            $goodstotal+= $count;
            $val['buy_price'] = fmoney($goods['price'],false);
        }

        $youhuitotal = $this->_checkyouhui($goodstotal);//默认满减 满50 减 5元 ；规则满减之后 再检测是否符合包邮标准
        $postfee = $this->_postfee($youhuitotal);

        $this->view->assign('cartids',$cart_ids);// 购物车id串
        $this->view->assign('goodstotal',fmoney($goodstotal,false));//商品总额
        $this->view->assign('postfee',fmoney($postfee,false));//配送费
        $this->view->assign('amount',fmoney($youhuitotal+$postfee,false));//总金额
        $this->view->assign('goodslist',$list);
        return $this->view->fetch();
    }

    /**
     * 配置配送费 不满99 + 6元配送费
     */
    private function _postfee($total){
        $re = 0;
        if($total<9900){
            $re = 600;
        }
        return $re;
    }


    /**
     * 检测默认优惠 满减 满50 减5
     * @param $total
     */
    private function _checkyouhui($total){
        if($total>5000){
            $total = $total-500;
        }
        return $total;
    }

}